package org.sakai.service.impl;

import org.sakai.entity.*;
import org.sakai.entity.dto.AIChatRequest;
import org.sakai.entity.dto.ChatMessage;
import org.sakai.mapper.AIConversationMapper;
import org.sakai.mapper.AIConversationMessageMapper;
import org.sakai.service.AIChatService;
import org.sakai.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;

import java.util.*;

@Service
public class AIChatServiceImpl implements AIChatService {
    
    // 定义支持的查询模式
    private static final List<String> SUPPORTED_MODES = Arrays.asList("naive", "local", "global", "hybrid");
    
    @Value("${ai.service.url:http://localhost:9621}")
    private String aiServiceUrl;
    
    @Value("${ai.service.api-key:AvengerOrange}")
    private String apiKey;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private AIConversationMapper conversationMapper;
    
    @Autowired
    private AIConversationMessageMapper messageMapper;
    
    @Override
    public Result<String> chat(AIChatRequest request) {
        // 1. 验证请求参数
        Result<String> validationResult = validateRequest(request);
        if (!validationResult.isSuccess()) {
            return validationResult;
        }
        
        try {
            // 2. 获取或创建会话
            AIConversation conversation = getOrCreateConversation(request);
            if (conversation == null) {
                return Result.error(ErrorCode.USER_NOT_FOUND_ERROR);
            }
            
            // 3. 保存用户消息
            saveMessage(conversation.getId(), request.getQuery(), AIConversationMessage.Sender.USER);
            
            // 4. 调用AI服务
            String aiResponse = callAIService(request);
            
            // 5. 保存AI响应
            saveMessage(conversation.getId(), aiResponse, AIConversationMessage.Sender.ASSISTANT);
            
            // 6. 更新会话最后活跃时间
            updateConversationActivity(conversation.getId());
            
            return Result.success(aiResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    private String getCurrentUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("x-access-token");
            if (token != null) {
                try {
                    Map<String, Object> claims = UserUtils.checkToken(token);
                    return (String) claims.get("uid");
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }
    
    private AIConversation getOrCreateConversation(AIChatRequest request) {
        String userId = getCurrentUserId();
        if (userId == null) {
            return null;
        }
        
        // 获取当前活跃会话
        AIConversation conversation = conversationMapper.getActiveConversation(userId);
        
        // 如果没有活跃会话，创建新会话
        if (conversation == null) {
            conversation = new AIConversation();
            conversation.setPatientId(userId);
            conversation.setStartAt(new Date());
            conversation.setLastActiveAt(new Date());
            conversation.setTimeoutSeconds(1800); // 30分钟超时
            conversation.setStatus(0); // ACTIVE
            conversationMapper.insert(conversation);
        } else {
            // 检查会话是否超时
            Date now = new Date();
            long diffSeconds = (now.getTime() - conversation.getLastActiveAt().getTime()) / 1000;
            if (diffSeconds > conversation.getTimeoutSeconds()) {
                // 会话超时，将状态设置为过期
                conversationMapper.updateStatus(conversation.getId(), 1); // EXPIRED
                
                // 创建新会话
                conversation = new AIConversation();
                conversation.setPatientId(userId);
                conversation.setStartAt(now);
                conversation.setLastActiveAt(now);
                conversation.setTimeoutSeconds(1800);
                conversation.setStatus(0);
                conversationMapper.insert(conversation);
            }
        }
        
        return conversation;
    }
    
    private void saveMessage(Long conversationId, String content, AIConversationMessage.Sender sender) {
        AIConversationMessage message = new AIConversationMessage();
        message.setConversationId(conversationId);
        message.setContent(content);
        message.setSender(sender.name());
        message.setCreatedAt(new Date());
        messageMapper.insert(message);
    }
    
    private void updateConversationActivity(Long conversationId) {
        conversationMapper.updateStatus(conversationId, 0); // 更新状态为ACTIVE
    }
    
    private String callAIService(AIChatRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-api-key", apiKey);
        
        Map<String, Object> payload = new HashMap<>();
        payload.put("query", request.getQuery());
        payload.put("mode", request.getMode());
        payload.put("response_type", "Multiple Paragraphs");
        payload.put("top_k", request.getTopK());
        
        // 处理历史对话记录
        if (request.getConversationHistory() != null && !request.getConversationHistory().isEmpty()) {
            List<Map<String, String>> history = new ArrayList<>();
            for (ChatMessage msg : request.getConversationHistory()) {
                Map<String, String> historyMsg = new HashMap<>();
                historyMsg.put("role", msg.getRole());
                historyMsg.put("content", msg.getContent());
                history.add(historyMsg);
            }
            payload.put("conversation_history", history);
        }
        
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
        
        ResponseEntity<Map> response = restTemplate.exchange(
            aiServiceUrl + "/query",
            HttpMethod.POST,
            entity,
            Map.class
        );
        
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Object responseData = response.getBody().get("response");
            if (responseData instanceof String) {
                return (String) responseData;
            } else if (responseData instanceof Map) {
                Map<String, Object> responseMap = (Map<String, Object>) responseData;
                if (responseMap.containsKey("data")) {
                    return (String) responseMap.get("data");
                } else if (responseMap.containsKey("message")) {
                    return (String) responseMap.get("message");
                }
            }
            throw new RuntimeException("AI响应格式不正确");
        }
        throw new RuntimeException("AI服务调用失败");
    }
    
    @Override
    public Result<String> validateRequest(AIChatRequest request) {
        // 1. 验证必填字段
        if (request == null) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getQuery() == null || request.getQuery().trim().isEmpty()) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getMode() == null || !SUPPORTED_MODES.contains(request.getMode())) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        
        // 2. 验证参数范围
        if (request.getTopK() != null && (request.getTopK() < 1 || request.getTopK() > 20)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getMaxTokenForTextUnit() != null && 
            (request.getMaxTokenForTextUnit() < 500 || request.getMaxTokenForTextUnit() > 8000)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getMaxTokenForGlobalContext() != null && 
            (request.getMaxTokenForGlobalContext() < 500 || request.getMaxTokenForGlobalContext() > 8000)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getMaxTokenForLocalContext() != null && 
            (request.getMaxTokenForLocalContext() < 500 || request.getMaxTokenForLocalContext() > 8000)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        if (request.getHistoryTurns() != null && (request.getHistoryTurns() < 0 || request.getHistoryTurns() > 10)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        
        return Result.success("验证通过");
    }
    
    /**
     * 处理朴素模式请求
     */
    private Result<String> handleNaiveMode(AIChatRequest request) {
        // TODO: 实现朴素模式的处理逻辑
        // 1. 构建提示词
        // 2. 调用AI模型
        // 3. 返回结果
        return Result.success("这是朴素模式的回复");
    }
    
    /**
     * 处理本地模式请求
     */
    private Result<String> handleLocalMode(AIChatRequest request) {
        // TODO: 实现本地模式的处理逻辑
        // 1. 检索相关文档
        // 2. 构建上下文
        // 3. 调用AI模型
        // 4. 返回结果
        return Result.success("这是本地模式的回复");
    }
    
    /**
     * 处理全局模式请求
     */
    private Result<String> handleGlobalMode(AIChatRequest request) {
        // TODO: 实现全局模式的处理逻辑
        // 1. 获取全局知识库内容
        // 2. 构建上下文
        // 3. 调用AI模型
        // 4. 返回结果
        return Result.success("这是全局模式的回复");
    }
    
    /**
     * 处理混合模式请求
     */
    private Result<String> handleHybridMode(AIChatRequest request) {
        // TODO: 实现混合模式的处理逻辑
        // 1. 检索相关文档
        // 2. 获取全局知识库内容
        // 3. 合并上下文
        // 4. 调用AI模型
        // 5. 返回结果
        return Result.success("这是混合模式的回复");
    }
} 